//
//  PersonalViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 1/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PersonalViewController.h"
#import "LoginViewController.h"
#import "ThemesView.h"
#import "ComprehensiveView.h"
#import "ZHDataService.h"

const NSInteger mesPageIndex = 1;

@interface PersonalViewController()
- (AbstractTabView *)loadTabViewWithTab:(PersonalCenterTab)tab;
- (AbstractTabView *)getExistedTabView:(PersonalCenterTab)tab;
@end

@implementation PersonalViewController

@synthesize notLoginLabel,tabView,contentView;
@synthesize comprehensiveButton,remindsButton,themesButton;
@synthesize currentTab;
@synthesize username,password,isAutoLogin;
@synthesize loginController;

#pragma mark - own methods
//create new tabview for different tab
- (AbstractTabView *)loadTabViewWithTab:(PersonalCenterTab)tab
{
    NSString *nibName = nil;
    switch (tab) {
        case kPersonalThemesTab:
            nibName = @"ThemesView";
            break;
        case kPersonalRepliesTab:
            nibName = @"ThemesView";
            break;
        default:
            nibName = @"ComprehensiveView";
            //load compresive view as default
        break;
    }
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
    AbstractTabView *abstarctView = (AbstractTabView *)[nibs lastObject];
    abstarctView.tag = tab;
    return abstarctView;
}
//get existed tab view in scrollview
- (AbstractTabView *)getExistedTabView:(PersonalCenterTab)tab
{
    AbstractTabView *av = nil;
    for(UIView* view in [self.contentView subviews])
    {
        if([view isKindOfClass:[AbstractTabView class]])
        {
            if(((AbstractTabView *)view).tag == tab)
            {
                view.hidden = NO;
                av = (AbstractTabView *)view;
            }
            else
                view.hidden = YES;
        }
    }
    return av;
}

- (IBAction)tabClicked:(UIButton *)sender
{
    //remove all sub tab views
    for(AbstractTabView *av in [self.contentView subviews])
        [av removeFromSuperview];
    
    self.comprehensiveButton.enabled = YES;
    self.remindsButton.enabled = YES;
    self.themesButton.enabled = YES;
    
    sender.enabled = NO;
    
    self.currentTab = (PersonalCenterTab)sender.tag;
    AbstractTabView *abstractView = [self getExistedTabView:self.currentTab];
    if(abstractView == nil)
    {
        abstractView = [self loadTabViewWithTab:sender.tag];
        [self.contentView addSubview:abstractView];
        abstractView.curTab = self.currentTab;
        //load infos 
        if(self.currentTab == kPersonalThemesTab || self.currentTab == kPersonalRepliesTab)
        {
            ThemesView *tv = (ThemesView *)abstractView;
            tv.currentPage = 1;
            [tv getPersonalMessagesWithPage:mesPageIndex];
        }
        else
        {
            ComprehensiveView *cv = (ComprehensiveView *)abstractView;
            [cv getLoginUserDataWithUsername:self.username andPassword:self.password autoLogin:self.isAutoLogin];
        }
    }
    else
    {
        [self.contentView bringSubviewToFront:abstractView];
    }
}

#pragma mark - AbstractTabViewController methods

- (void)leftItemClicked
{
    AbstractTabView *abstractView = [self getExistedTabView:self.currentTab];
    abstractView.curTab = self.currentTab;
    if(self.currentTab == kPersonalComprehensiveTab)
    {
        ComprehensiveView *cv = (ComprehensiveView *)abstractView;
        [cv getLoginUserDataWithUsername:self.username andPassword:self.password autoLogin:self.isAutoLogin];
    }
    else
    {
        //load infos 
        ThemesView *tv = (ThemesView *)abstractView;
        tv.currentPage = 1;
        [tv getPersonalMessagesWithPage:mesPageIndex];
    }
}
- (void)rightItemClicked
{
    if([ZHDataService isLogined])
    {
        [ZHDataService logout];
        LoginViewController *lc = [[LoginViewController alloc] init];
        self.loginController = lc;
        self.loginController.name = nil;
        self.loginController.pwd = nil;
        self.loginController.isAuto = NO;
        [self presentModalViewController:loginController animated:YES];
        [loginController release];
    }
    else {
        LoginViewController *lc = [[LoginViewController alloc] init];
        self.loginController = lc;
        self.loginController.name = self.username;
        self.loginController.pwd = self.password;
        self.loginController.isAuto = self.isAutoLogin;
        [self presentModalViewController:loginController animated:YES];
        [loginController release];
    }
}

#pragma mark - View lifecycle
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [loginController release];
    [username release];
    [password release];
    [contentView release];
    [tabView release];
    [notLoginLabel release];
    [remindsButton release];
    [themesButton release];
    [comprehensiveButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(![ZHDataService isLogined])
    {
        self.navigationItem.rightBarButtonItem.title = @"登录";
        self.tabView.hidden = YES;
        self.contentView.hidden = YES;
        self.notLoginLabel.hidden = NO;
        [self rightItemClicked];
    }
    else
    {
        self.navigationItem.rightBarButtonItem.title = @"注销";
//        self.navigationItem.rightBarButtonItem = nil;
        self.tabView.hidden = NO;
        self.contentView.hidden = NO;
        self.notLoginLabel.hidden = YES;
        if(self.currentTab == kPersonalComprehensiveTab)
        {
            //register succeed then dismiss, relogin with the accout
            if([[ZHDataService sharedService].loginUser.userId isEqualToString:@"registered"])
                [self tabClicked:self.comprehensiveButton];
        }
        else if(self.currentTab == kPersonalThemesTab)
            [self tabClicked:self.themesButton];
        else
            [self tabClicked:self.remindsButton];
    }
}

- (void)userLogined
{
    if(nil != self.loginController)
        [self.loginController dismissModalViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人中心";
    [self addNaviBarLeftRefreshItem];
    [self addNaviBarRightItemWithTitle:@"登录"];
    [self setBackgroundImageViewForTabView];
    self.currentTab = kPersonalComprehensiveTab;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLogined) name:kUserLoginedNotification object:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.comprehensiveButton = nil;
    self.remindsButton = nil;
    self.themesButton = nil;
    self.notLoginLabel = nil;
    self.tabView = nil;
    self.contentView = nil;
}
@end
